package com.atguigu.lease.admin.controller.system;

import com.atguigu.lease.admin.service.SystemUserService;
import com.atguigu.lease.common.result.Result;
import com.atguigu.lease.model.bean.SystemUser;
import com.atguigu.lease.model.vo.system.SystemUserItemVo;
import com.atguigu.lease.model.vo.system.SystemUserQueryVo;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Tag(name = "后台用户管理模块")
@RestController
@RequestMapping("/admin/system/user")
public class SystemUserController {
    @Autowired
    SystemUserService systemUserService;
    @Operation(summary = "3、新增或更新用户")
    @PostMapping("/saveOrUpdate")
    public Result saveOrUpdate(@RequestBody SystemUser systemUser) {
        systemUserService.saveOrUpdateSystemUser(systemUser);
        return Result.ok();
    }
    @Operation(summary = "2、新增更新用户时检查用户名是否可用")
    @GetMapping("/isUserNameAvailable")
    public Result<Boolean> isUserNameAvailable(@RequestParam(required = false) Long id,
                                                   @RequestParam String username){
        //id不为空： 表示更新
        //   如果systemuser表存在 id不等于更新用户的id，username等于更新用户的username，表示用户名被占用！
//        if(id!=null){
//            long count = systemUserService.count(Wrappers.lambdaQuery(SystemUser.class)
//                    .ne(SystemUser::getId, id) //ne :not eq
//                    .eq(SystemUser::getUsername, username));
//            // count等于0表示：id和自己不一样的用户，没有用户使用username
//            return Result.ok(count == 0);
//        }
//        //id为空：表示新增
//        //  如果用户名已存在 用户名被占用
//        long count = systemUserService.count(Wrappers.lambdaQuery(SystemUser.class)
//                .eq(SystemUser::getUsername, username));

        long count = systemUserService.count(Wrappers.lambdaQuery(SystemUser.class)
        .ne(id!=null , SystemUser::getId, id) //ne :not eq
        .eq(SystemUser::getUsername, username));
        return Result.ok(count==0);
    }

    @Operation(summary = "1、条件分页查询后台用户")
    @GetMapping("/page")
    public Result<Page<SystemUserItemVo>> pageItem(@RequestParam Long current,
                                                   @RequestParam Long size,
                                                   SystemUserQueryVo queryVo){
        return Result.ok(systemUserService.pageItem(current,size,queryVo));
    }
}
